import { useContext } from 'react'
import { matchPath, useLocation, useOutlet } from 'react-router-dom'
import { KeepAliveContext } from '@/components/KeepAlive'

const isKeepPath = (keepPaths: Array<string | RegExp>, path: string) => {
  let isKeep = false
  for (let i = 0; i < keepPaths.length; i++) {
    const item = keepPaths[i]
    if (item === path) {
      isKeep = true
    }
    if (item instanceof RegExp && item.test(path)) {
      isKeep = true
    }
    if (typeof item === 'string' && item.toLowerCase() === path) {
      isKeep = true
    }
  }
  return isKeep
}

function useKeepOutlet() {
  const localtion = useLocation()
  const element = useOutlet()
  const { keepPaths, keepElements } = useContext(KeepAliveContext)
  const isKeep = isKeepPath(keepPaths, localtion.pathname)
  if (isKeep) {
    keepElements[localtion.pathname] = element
  }
  return (
    <>
      {Object.entries(keepElements).map(([pathname, element]) => (
        <div
          key={pathname}
          //   style={{
          //     height: "100%",
          //     width: "100%",
          //     position: "relative",
          //     overflow: "hidden auto",
          //   }}
          hidden={!matchPath(localtion.pathname, pathname)}
        >
          {element}
        </div>
      ))}
      {!isKeep && element}
    </>
  )
}

export default useKeepOutlet
